package cmdShop;

//cmdShop - Craftbukkit plugin to integrate BOSEconomy 
//with PermissionsEx in order to facilitate
//the purchase of player prefixes and permissions
//while appropriately managing player account 
//balances.  The most common use would be to 
//configure a command block to call this plugin. 
//
//Why do I need this plugin?  
//========================== 
//Without this plugin, a command block can only 
//be configured to take a series of actions:  add
//the permission, take the money... with no logical
//dependency between the actions.  Since BOSEconomy
//allows negative account balances, the net effect
//is that users can "buy" anything regardless of 
//their balance.  This plugin corrects that problem by 
//guaranteeing that users have a balance sufficient
//to pay for the item they are purchasing and, if not,
//it disallows the purchase.
//
//After calling this plugin, be sure to do a: 
//pex reload
//
//Tested with craftbukkit 1.5.2R1, 
//BOSEconomy 0.7.6.3 and PermissionsEx 1.19.6. 
//
//THIS PLUGIN IS ABSOLUTELY UNSUPPPORTED --
//AND UNDOCUMENTED  -- 
//USE AT YOUR OWN RISK! 
//
//E-mail  - urbancraftcreativeserver@gmail.com


import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;

import ru.tehkode.permissions.PermissionUser;
import ru.tehkode.permissions.bukkit.PermissionsEx;
import cosine.boseconomy.BOSEconomy;

public class cmdShop extends JavaPlugin{
	//This variable will store the reference to BOSEconomy.
	BOSEconomy economy = null;
	
	@Override
	public void onDisable() {
		System.out.println("[cmdShop] plugin disabled"); 
	}
	
	@Override
	public void onEnable() {
		PluginManager pm = this.getServer().getPluginManager();
		pm.registerEvents(new cmdShopListener(this), this);
		loadBOSEconomy();
		System.out.println("[cmdshop] plugin enabled"); 
	}
	
	public void loadBOSEconomy(){
		// Attempt to get the plugin instance for BOSEconomy.
		Plugin temp = this.getServer().getPluginManager().getPlugin("BOSEconomy");
	
		// Check whether BOSEconomy is loaded.
		if(temp == null){
			// BOSEconomy is not loaded on the server.
			economy = null;
			System.out.println("[cmdshop] BOSEconomy not loaded on the server");
		}
		else {
			// BOSEconomy is now stored in the "economy" variable.
			economy = (BOSEconomy)temp;
		}
	}
	
	public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    	Player player = null;
		
    	if (cmd.getName().equalsIgnoreCase("cmdshop")){ // If the player typed /cmdshop then do the following...
    		//System.out.println("/cmdshop command received");
    		
    		// Check the number of arguments...
    		if ( args.length != 4 ) {
    			System.out.println("[cmdshop] check arguments-- wrong number received"); 			
    			displayHelp(sender);
    			return false;
    		}
    		    		
    		if (sender instanceof Player) {
        		player = (Player) sender; 	
        		if(player.hasPermission("cmdshop.execute")){
    				System.out.println("[cmdshop] user "+ args[0]+" has permission to execute");
    				doCmdShop(args[0], args[1], args[2], args[3]);
    			}
        		else {
        			System.out.println("Player "+ args[0] +" does not have execute permission");
        			return false;
        		}
    		}
    		else {
    			// It must be a command block that is calling us... 
    			System.out.println("[cmdshop] plugin called from command block");
    			doCmdShop(args[0], args[1], args[2], args[3]);
    		}
    		return true;
    	}
    	return false;
    }

	private void displayHelp(CommandSender sndr) {
		Player player = null;
		
		if (sndr instanceof Player) {
    		player = (Player) sndr;
    		player.sendMessage(ChatColor.GOLD +"[cmdshop] Incorrect usage.  Use: /cmdshop <player> <purchase price> <prefix|add> <[Tag]|node.node>");
		}	
		else {
			System.out.println("[cmdshop] Incorrect usage.  Use: /cmdshop <player> <purchase price> <prefix|add> <[Tag]|node.node>");
		}
	}
	
	private boolean doCmdShop(String playerName, String PurchaseStr, String permtype, String permission ) {
		
		double PurchaseAmt = Double.parseDouble(PurchaseStr);
		double CurrentBalance = economy.getPlayerMoneyDouble(playerName);
		
		Player p = getServer().getPlayer(playerName); 	
		PermissionUser user = PermissionsEx.getUser(p);
		
		String worldName = p.getWorld().getName();

		if (PurchaseAmt > CurrentBalance) {
			System.out.println("[cmdshop] player "+playerName+" has insufficent balance to complete purchase");
			p.sendMessage(ChatColor.RED + "[Shop] Sorry, but your balance is too low to complete this purchase.");
			return false;
		}
		else {
			// Take his money... 
			economy.addPlayerMoney(playerName, (PurchaseAmt*-1), true);
			
			// Give him what he purchased...  
			if (permtype.intern() == "prefix"){
				System.out.println("[cmdshop] adding prefix " + permission + " to player "+playerName);
				user.setPrefix(permission, worldName.intern());
				//Print message back to user... transaction completed.
				p.sendMessage(ChatColor.GOLD + "[Shop] Thank you for your purchase. Your prefix has been added.");
			}
			else {
				if (permtype.intern() == "add") {
					System.out.println("[cmdshop] adding permission " + permission + " to player "+playerName);
					user.addPermission(permission, worldName.intern());
										
					//Print message back to user... transaction completed. 
					p.sendMessage(ChatColor.GOLD + "[Shop] Thank you for your purchase. Your permission has been added.");
				}
				else {
					System.out.println("[cmdshop] permission type must be prefix or add as third parameter");
				}
			}
		}	
		return true;
	}	
}
